import React, { Component } from 'react';
import { Toast } from 'antd-mobile'
import { get_register } from '../utils/api'
class Register extends Component {
    state = {
        phone: "",
        pass: "",
        checkpass: ""
        
    }


    //跳转到登录页面
    handleLogin() {
        this.props.history.push({ pathname: '/login' })
    }



    handleChange(e) {
        // console.log(e.target.name);
        this.setState({//this.setState 本身是通过异步方法的方式保存数据到state，所以不能在其之后立马获取最新的state，如果想要获取最新的state 只能在setState的回调函数中获取
            [e.target.name]: e.target.value
        }, () => {//可以省略
            // console.log(this.state);
        })
    }

    register() {
        //电话正则验证
        let isPhone =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;
        if (this.state.phone === '' || this.state.pass === '' || this.state.checkpass === '') {
            Toast.show({ icon: 'fail', content: '不能为空' })
        } else {
            if (isPhone.test(this.state.phone) === false) {
                Toast.show({ icon: 'fail', content: '请输入正确手机号' })
            } else if (this.state.pass !== this.state.checkpass) {
                Toast.show({ icon: 'fail', content: '两次输入密码不一致' })
            } else {
                let { checkpass, ...params } = this.state
                get_register(params).then((res) => {
                    Toast.show({ icon: 'fail', content: res.data.msg })
                    //跳转到登录页
                    this.handleLogin()
                })
            }
        }
    }

    render() {
        return (
            <div className='register'>
                <div className="Box">
                    <div className="odiv user">
                        <input type="text" name='phone' value={this.state.phone} onChange={(e) => { this.handleChange(e) }} placeholder="请输入用户名" />
                    </div>
                    <div className="odiv pass">
                        <input type="password" name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} placeholder="请输入密码" />
                    </div>
                    <div className="odiv pass">
                        <input type="password" name='checkpass' value={this.state.checkpass} onChange={(e) => { this.handleChange(e) }} placeholder="请再次输入密码" />
                    </div>
                    <div className="odiv btn">
                        <input type="button" onClick={() => { this.register() }} value="注册" />
                    </div>
                    <div className='odiv reg'><span onClick={() => { this.handleLogin() }}>登录</span></div>
                </div>
            </div>
        );
    }
}

export default Register;